const router = require('../../router');
const courseModel = require('../../../model/course')
const courseItemModel = require('../../../model/courseItem')
const orderModel = require('../../../model/order')

router.get('/course/:category', async (ctx) => {
    const category = ctx.params.category
    const result = await courseModel.findAll({
        where: {
            category
        },
        order: [['id', 'DESC']],
    })

    const resultPromise = []
    result.forEach(e => {
        const promiseItem = courseItemModel.findAll({
            where: {
                courseId: e.id
            }
        })
        resultPromise.push(promiseItem)
    })

    const goumai = await orderModel.findAll({
        where: {status: 1, userId: ctx.session.userLoginId}
    })
    const goumaiArr = [];
    goumai.forEach(e => {
        goumaiArr.push(e.courseId)
    })

    Object.assign(ctx.viewData, {
        topCategory: 'course',
        category: ctx.params.category,
        list: result,
        goumaiArr: goumaiArr,
        courseItem: await Promise.all(resultPromise)
    })

    ctx.body = await ctx.render('course/index', ctx.viewData)
})